﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Carto;
using MyEngineExercise.我的扩展;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geometry;
using System.Diagnostics;
using MyEngineExercise.我的扩展.图层扩展类;
using stdole;

namespace MyEngineExercise.工作.兴宁出图_20121110
{
    public partial class ExportForm : Form
    {

        private MyAeMethods _myAeMethods = null;

        public ExportForm(MyAeMethods myAeMethods)
        {
            InitializeComponent();

            _myAeMethods = myAeMethods;

            IFeatureClass ploygonFeatureClass = _myAeMethods.NewFeatureClass(@"D:\My Documents\Downloads\兴宁处理\测试结果2012_11_08_1642\刁坊镇\原输出坐标检查\2012_11_8_16_42_54\刁坊镇权属区\刁坊镇权属区.shp");
            IFeatureClass pointFeatureClass = null;
            IFeatureClass lineFeatureClass = null;
            IFeatureWorkspace featureWorkspace = _myAeMethods.NewMdbFeatureWorkspace(@"D:\My Documents\Downloads\兴宁处理\测试结果2012_11_08_1642\刁坊镇\原输出坐标检查\2012_11_8_16_42_54\刁坊镇.mdb");
            pointFeatureClass = featureWorkspace.OpenFeatureClass("景标界址点");
            lineFeatureClass = featureWorkspace.OpenFeatureClass("景标界址线");
            string mdbPath = @"D:\资料\luo\兴宁农村集体土地登记发证a4模版一.mxd";


            string qsdwm = "郑江村聚华屋经济合作社";

            string searchMan_str = "也一样";
            string makeMan_str = "也一样";
            string checkMan_str = "也一样";

            string searchDate = "5000年十一月十三日";
            string makeDate = "5000年十一月十三日";
            string checkDate = "5000年十一月十三日";
      

            this.axPageLayoutControl1.LoadMxFile(mdbPath);

            EnumLayerClass enumLayerClass = new EnumLayerClass();

            IFeatureLayer featureLayer_line = new FeatureLayerClass(); featureLayer_line.FeatureClass = lineFeatureClass;
            IFeatureLayer featureLayer_point = new FeatureLayerClass(); featureLayer_point.FeatureClass = pointFeatureClass;
            IFeatureLayer featureLayer_polygon = new FeatureLayerClass(); featureLayer_polygon.FeatureClass = ploygonFeatureClass;

            featureLayer_point.Name = "界址点";
            featureLayer_line.Name = "界址线";
            featureLayer_polygon.Name = "权属区";

            enumLayerClass.AddLayerToList(featureLayer_line);
            enumLayerClass.AddLayerToList(featureLayer_point);
            enumLayerClass.AddLayerToList(featureLayer_polygon);

            this.axPageLayoutControl1.ActiveView.FocusMap.AddLayers(enumLayerClass,true);

            IGeoFeatureLayer geoFeatureLayer_point = (IGeoFeatureLayer)featureLayer_point;
            IGeoFeatureLayer geoFeatureLayer_line = (IGeoFeatureLayer)featureLayer_line;
            IGeoFeatureLayer geoFeatureLayer_polygon = (IGeoFeatureLayer)featureLayer_polygon;

            this.axPageLayoutControl1.Page.FormID = esriPageFormID.esriPageFormA4;

            IFeatureCursor featureCursor = ploygonFeatureClass.Search(null,false);
            IFeature feature = null;

            List<IFeature> featureList = new List<IFeature>();//某一权属单位名对应feature list
            List<string> diji_num_list = new List<string>();//某一权属单位名对应地籍号（不重复）


            string fieldName_qsdwm = "权属单位名";//字段名
            int index_qsdwm = ploygonFeatureClass.Fields.FindField(fieldName_qsdwm);//字段索引
            string fieldName_djh = "地籍号";//字段名
            int index_djh = ploygonFeatureClass.Fields.FindField(fieldName_djh);//字段索引
            string fieldName_tfh = "所在图幅号";//字段名
            int index_tfh = ploygonFeatureClass.Fields.FindField(fieldName_tfh);//字段索引

            string fieldName_txmj = "宗地面积";//宗地面积


            double area = 0;//面积
            string tfh_str = string.Empty;//第一个图幅号

            IDataStatistics dataStatistics = new DataStatisticsClass();
            dataStatistics.Field = fieldName_tfh;


            //根据权属单位名，获取地籍号
            while(null != (feature = featureCursor.NextFeature()))
            {
                string value_qsdwm = feature.get_Value(index_qsdwm).ToString();//权属单位名
                string value_djh = feature.get_Value(index_djh).ToString();//地籍号
                string value_tfh = feature.get_Value(index_tfh).ToString();//图幅号

                //都渲染为同一个样式
                if (value_qsdwm == qsdwm)
                {
                    featureList.Add(feature);
                    if (diji_num_list.Contains(value_djh) == false)
                    {
                        diji_num_list.Add(value_djh);
                        area += ((IArea)feature.Shape).Area;
                        if (tfh_str == string.Empty)
                        {
                            tfh_str = value_tfh;
                        }
                    }
                }
            }

            #region 渲染图层
            #region 渲染点图层
            ICharacterMarkerSymbol characterMarkerSymbol1 = new CharacterMarkerSymbolClass();
            StdFont stdFont1 = new StdFont();
            stdFont1.Name = "ESRI Default Marker";//一定要设置这个
            stdFont1.Size = 2;
            characterMarkerSymbol1.Font = (IFontDisp)stdFont1;
            characterMarkerSymbol1.CharacterIndex = 33;
            characterMarkerSymbol1.Size = 8;
            IRgbColor rgbColor_point = new RgbColorClass();
            rgbColor_point.Red = 255;
            rgbColor_point.Green = 255;
            rgbColor_point.Blue = 255;
            characterMarkerSymbol1.Color = rgbColor_point;

            ICharacterMarkerSymbol characterMarkerSymbol2 = new CharacterMarkerSymbolClass();
            StdFont stdFont2 = new StdFont();
            stdFont2.Name = "ESRI Default Marker";//一定要设置这个
            stdFont2.Size = 2;
            characterMarkerSymbol2.Font = (IFontDisp)stdFont2;
            characterMarkerSymbol2.CharacterIndex = 46;
            characterMarkerSymbol2.Size = 8;
            IRgbColor rgbColor_point2 = new RgbColorClass();
            rgbColor_point2.Red = 255;
            rgbColor_point2.Green = 0;
            rgbColor_point2.Blue = 0;
            characterMarkerSymbol2.Color = rgbColor_point2;

            IMultiLayerMarkerSymbol multiLayerMarkerSymbol = new MultiLayerMarkerSymbolClass();
            multiLayerMarkerSymbol.AddLayer(characterMarkerSymbol1);
            multiLayerMarkerSymbol.AddLayer(characterMarkerSymbol2);

            var simpleRenderer_point = new SimpleRendererClass();
            simpleRenderer_point.Symbol = (ISymbol)multiLayerMarkerSymbol;
            geoFeatureLayer_point.Renderer = (IFeatureRenderer)simpleRenderer_point;
            #endregion

            #region 渲染线图层
            //ILayer layer_line = this.axPageLayoutControl1.ActiveView.FocusMap.get_Layer(1);
            //IFeatureLayer featureLayer_line = (IFeatureLayer)layer_line;
            //IGeoFeatureLayer geoFeatureLayer_line = (IGeoFeatureLayer)featureLayer_line;
            //边线颜色，红色
            IRgbColor rgbColor = new RgbColorClass();
            rgbColor.Red = 255;
            rgbColor.Green = 0;
            rgbColor.Blue = 0;
            //边线样式
            ILineSymbol lineSymbol = new SimpleLineSymbolClass();
            lineSymbol.Color = rgbColor;
            lineSymbol.Width = 1.2;
            var simpleRenderer_line = new SimpleRendererClass();
            simpleRenderer_line.Symbol = (ISymbol)lineSymbol;
            geoFeatureLayer_line.Renderer = (IFeatureRenderer)simpleRenderer_line;
            #endregion

            #region 渲染面图层
            IRgbColor rgbColor_polygon = new RgbColorClass();
            rgbColor_polygon.Red = 0;
            rgbColor_polygon.Green = 0;
            rgbColor_polygon.Blue = 255;
            
            //填充颜色，唔、无
            IColor nullColor = new RgbColorClass();
            nullColor.NullColor = true;
            ILineSymbol lineSymbol_polygon = new SimpleLineSymbolClass();
            lineSymbol_polygon.Color = rgbColor_polygon;
            lineSymbol_polygon.Width = 1.2;
            //填充样式
            IFillSymbol fillSymbol = new SimpleFillSymbolClass();
            fillSymbol.Outline = lineSymbol_polygon;//边线
            fillSymbol.Color = nullColor;//内部填充
            //fillSymbol.Color.NullColor = true; // 直接设置不会产生效果！
            var simpleRenderer_polygon = new SimpleRendererClass();
            simpleRenderer_polygon.Symbol = (ISymbol)fillSymbol;
            geoFeatureLayer_polygon.Renderer = (IFeatureRenderer)simpleRenderer_polygon;
            #endregion
            #endregion

            #region 隐藏不需要的点和线
            //定义查询,注意目标文件是mdb，不能用"地籍号"，应该用[地籍号]
            string whereStr_definitionQuery = string.Empty;
            if (diji_num_list.Count == 1)
            {
                whereStr_definitionQuery = string.Format("[{0}] = '{1}'", fieldName_djh, diji_num_list.First());
            }
            else if (diji_num_list.Count > 1)
            {
                foreach (var sdf in diji_num_list)
                {
                    whereStr_definitionQuery += string.Format("[{0}] = '{1}' OR ", fieldName_djh, sdf);
                }
                whereStr_definitionQuery = whereStr_definitionQuery.Substring(0, whereStr_definitionQuery.LastIndexOf("OR"));
            }
            else
            {
                MessageBox.Show("发生错误");
            }
            //ILayer layer_point = this.axPageLayoutControl1.ActiveView.FocusMap.get_Layer(0);
            //IFeatureLayer featureLayer_point = (IFeatureLayer)layer_point;
            IFeatureLayerDefinition2 featureLayerDefinition_point = (IFeatureLayerDefinition2)featureLayer_point;
            featureLayerDefinition_point.DefinitionExpression = whereStr_definitionQuery;
            IFeatureLayerDefinition2 featureLayerDefinition_line = (IFeatureLayerDefinition2)featureLayer_line;
            featureLayerDefinition_line.DefinitionExpression = whereStr_definitionQuery;
            #endregion

            #region 移动到中心点
            IPolygon unionPolygon = _myAeMethods.UnionPolygons(((IGeoDataset)ploygonFeatureClass).SpatialReference, featureList);
            IEnvelope envelop = unionPolygon.Envelope;
            envelop.Expand(10, 10, false);
            IPoint pt1 = ((IArea)envelop).Centroid;
            IPoint pt2 = ((IArea)(((IActiveView)this.axPageLayoutControl1.ActiveView.FocusMap).Extent)).Centroid;
            ((IActiveView)this.axPageLayoutControl1.ActiveView.FocusMap).ScreenDisplay.PanStart(pt1);
            ((IActiveView)this.axPageLayoutControl1.ActiveView.FocusMap).ScreenDisplay.PanMoveTo(pt2);
            ((IActiveView)this.axPageLayoutControl1.ActiveView.FocusMap).ScreenDisplay.PanStop();
            #endregion

            #region 设置extent
            //double temp = 25;
            //IEnvelope envelop_layout = new EnvelopeClass();
            //envelop_layout.PutCoords(envelop.LowerLeft.X - temp, envelop.LowerLeft.Y - temp, envelop.UpperRight.X + temp, envelop.UpperRight.Y + temp);
            ((IActiveView)this.axPageLayoutControl1.ActiveView.FocusMap).Extent = envelop;
            //设置比例尺，要500的倍数
            this.axPageLayoutControl1.ActiveView.FocusMap.MapScale = (500 - (this.axPageLayoutControl1.ActiveView.FocusMap.MapScale - ((int)(this.axPageLayoutControl1.ActiveView.FocusMap.MapScale / 500)) * 500)) + this.axPageLayoutControl1.ActiveView.FocusMap.MapScale;
            #endregion

            #region 重新设置element的值
            //
            IElement element = null;
            List<IElement> elements = new List<IElement>();
            IGraphicsContainer graphicsContainer = (IGraphicsContainer)this.axPageLayoutControl1.PageLayout;
            while (null != (element = graphicsContainer.Next()))
            {
                elements.Add(element);
            }
            //设置副标题
            IElement qsdwName = elements.FirstOrDefault<IElement>(v => ((IElementProperties3)v).Name.Equals("qsdwmElementName"));
            ITextElement textElement_qsdw = (ITextElement)qsdwName;
            textElement_qsdw.Text = qsdwm + "\n" + diji_num_list.Aggregate((a,b) => a + "、" + b);
            //设置比例尺
            IElement blcName = elements.FirstOrDefault<IElement>(v => ((IElementProperties3)v).Name.Equals("scaleElementName"));
            ITextElement textElement_blc = (ITextElement)blcName;
            textElement_blc.Text = string.Format("1：{0}",this.axPageLayoutControl1.ActiveView.FocusMap.MapScale.ToString());
            //设置面积
            IElement areaName = elements.FirstOrDefault<IElement>(v => ((IElementProperties3)v).Name.Equals("areaElementName"));
            ITextElement textElement_area = (ITextElement)areaName;
            textElement_area.Text = (area/10000).ToString("0.0000");
            //设置图幅号
            IElement tfhName = elements.FirstOrDefault<IElement>(v => ((IElementProperties3)v).Name.Equals("tfhElementName"));
            ITextElement textElement_tfh = (ITextElement)tfhName;
            textElement_tfh.Text = tfh_str;
            //设置调查日期
            IElement searchDateName = elements.FirstOrDefault<IElement>(v => ((IElementProperties3)v).Name.Equals("searchDateElementName"));
            ITextElement textElement_searchDate = (ITextElement)searchDateName;
            textElement_searchDate.Text = searchDate;
            //设置制图日期
            IElement makeDateName = elements.FirstOrDefault<IElement>(v => ((IElementProperties3)v).Name.Equals("makeMapDateElementName"));
            ITextElement textElement_makeDate = (ITextElement)makeDateName;
            textElement_makeDate.Text = makeDate;
            //设置审核日期
            IElement checkDateName = elements.FirstOrDefault<IElement>(v => ((IElementProperties3)v).Name.Equals("checkDateElementName"));
            ITextElement textElement_checkDate = (ITextElement)checkDateName;
            textElement_checkDate.Text = checkDate;

            //设置调查员
            IElement searchManName = elements.FirstOrDefault<IElement>(v => ((IElementProperties3)v).Name.Equals("searchManElementName"));
            ITextElement textElement_searchMan = (ITextElement)searchManName;
            textElement_searchMan.Text = searchMan_str;
            //设置制图人
            IElement makeManName = elements.FirstOrDefault<IElement>(v => ((IElementProperties3)v).Name.Equals("makeManElementName"));
            ITextElement textElement_makeMan = (ITextElement)makeManName;
            textElement_makeMan.Text = makeMan_str;
            //设置审核员
            IElement checkManName = elements.FirstOrDefault<IElement>(v => ((IElementProperties3)v).Name.Equals("checkManElementName"));
            ITextElement textElement_checkMan = (ITextElement)checkManName;
            textElement_checkMan.Text = checkMan_str;
            #endregion

            #region 设置权属面的lable

            #region 样式一
            IAnnotateLayerPropertiesCollection poly_annotateLayerProtiesCol = (IAnnotateLayerPropertiesCollection)geoFeatureLayer_polygon.AnnotationProperties;
            IAnnotateLayerProperties poly_annotateLayerProties = null;
            IElementCollection poly_placedElements = null;
            IElementCollection poly_unplacedElements = null;
            poly_annotateLayerProtiesCol.QueryItem(0, out poly_annotateLayerProties, out poly_placedElements, out poly_unplacedElements);

            //设置样式一的字体，显示字段
            var poly_labelEngineLayerProperties = (ILabelEngineLayerProperties2)poly_annotateLayerProties;
            // 设置标注的字体及颜色
            ITextSymbol polyLabelTextSymbol = new ESRI.ArcGIS.Display.TextSymbolClass();
            polyLabelTextSymbol.Size = 12;
            polyLabelTextSymbol.Font.Name = "新宋体";
            polyLabelTextSymbol.Color = rgbColor_polygon;
            poly_labelEngineLayerProperties.IsExpressionSimple = true;
            poly_labelEngineLayerProperties.Expression = string.Format("[{0}]", fieldName_qsdwm);//注意这里  [xxx]
            poly_labelEngineLayerProperties.Symbol = polyLabelTextSymbol;

            

            //label样式一过滤条件,注意目标文件是shape，不能用[地籍号]，应该"地籍号"，不能单引号
            string whereStr_label_style_one = string.Empty;
            /*if (diji_num_list.Count == 1)
            {
                whereStr_label_style_one = string.Format("\"{0}\" <> '{1}'", fieldName_djh, diji_num_list.First());
            }
            else if (diji_num_list.Count > 1)
            {
                foreach (var sdf in diji_num_list)
                {
                    whereStr_label_style_one += string.Format("\"{0}\" <> '{1}' OR ", fieldName_djh, sdf);
                }
                whereStr_label_style_one = whereStr_label_style_one.Substring(0, whereStr_label_style_one.LastIndexOf("OR"));
            }
            else
            {
                MessageBox.Show("发生错误");
            }*/
            whereStr_label_style_one = string.Format("\"{0}\" <> '{1}'", fieldName_qsdwm, qsdwm);

            //MessageBox.Show(whereStr_label_style_one);
            //Debug.Print(whereStr_label_style_one);

            poly_annotateLayerProties.WhereClause = whereStr_label_style_one;
            // 必须同时使用这两个选项才能显示标注
            poly_annotateLayerProties.DisplayAnnotation = true;
            #endregion

            #region 样式二
            IAnnotateLayerPropertiesCollection annotateLayerPropertiesCollection = (IAnnotateLayerPropertiesCollection)geoFeatureLayer_polygon.AnnotationProperties;
            //创建一个标注类
            IAnnotateLayerProperties annotateLayerProperties_1 = new ESRI.ArcGIS.Carto.LabelEngineLayerPropertiesClass();
            annotateLayerProperties_1.Class = "bill_1";
            annotateLayerProperties_1.DisplayAnnotation = true;
            annotateLayerProperties_1.FeatureLayer = geoFeatureLayer_polygon;
            annotateLayerPropertiesCollection.Add(annotateLayerProperties_1);

            IAnnotateLayerProperties annotateLayerProperties = null;
            IElementCollection elementCollection_place = null;
            IElementCollection elementCollection_unPlace = null;
            //注意这里的“1”，在图层上一定要有2个label类
            annotateLayerPropertiesCollection.QueryItem(1, out annotateLayerProperties, out elementCollection_place, out elementCollection_unPlace);
            //设置样式一的字体，显示字段
            var labelEngineLayerProperties2 = (ILabelEngineLayerProperties2)annotateLayerProperties;
            // 设置标注的字体及颜色
            ITextSymbol textSymbol = new ESRI.ArcGIS.Display.TextSymbolClass();
            textSymbol.Size = 12;
            textSymbol.Color = rgbColor;
            textSymbol.Font.Name = "新宋体";

            //labelEngineLayerProperties2.Expression = string.Format("[{0}]  & chr(13) & [{1}] & chr(13) & ROUND([{2}]/10000,4)", fieldName_qsdwm, fieldName_djh, fieldName_txmj);//注意这里  [xxx]
            
            //labelEngineLayerProperties2.Expression = string.Format("[{0}]  & chr(13) & [{1}] & chr(13) & cstr(ROUND([{2}]/10000,4))", fieldName_qsdwm, fieldName_djh, fieldName_txmj);//注意这里  [xxx]

            //label样式一过滤条件,注意目标文件是shape，不能用[地籍号]，应该"地籍号"，不能单引号
            string whereStr_label_style_two = string.Empty;
            if (diji_num_list.Count == 1)
            {
                whereStr_label_style_two = string.Format("\"{0}\" = '{1}'", fieldName_djh, diji_num_list.First());
            }
            else if (diji_num_list.Count > 1)
            {
                foreach (var sdf in diji_num_list)
                {
                    whereStr_label_style_two += string.Format("\"{0}\" = '{1}' OR ", fieldName_djh, sdf);
                }
                whereStr_label_style_two = whereStr_label_style_two.Substring(0, whereStr_label_style_two.LastIndexOf("OR"));
            }
            else
            {
                MessageBox.Show("发生错误");
            }

            //whereStr_label_style_one = string.Format("\"{0}\" = '{1}'", fieldName_qsdwm, qsdwm);

            annotateLayerProperties.WhereClause = whereStr_label_style_two;

            //用javascript写过滤条件
            IAnnotationExpressionEngine annotationExpressionEngine = new AnnotationJScriptEngine();
            var strCode = "function FindLabel ( [地籍号],[权属单位名] ,[宗地面积]  ){var p = [权属单位名] + \"\\r\" +  [地籍号] + \"\\r\" + (parseFloat([宗地面积]/10000)).toFixed(4).toString()  ;return p;}";
            Console.WriteLine(strCode);
            Console.WriteLine(annotationExpressionEngine.Name);
            annotationExpressionEngine.SetCode(strCode, "FindLabel");
            labelEngineLayerProperties2.ExpressionParser = annotationExpressionEngine;
            labelEngineLayerProperties2.IsExpressionSimple = false;//用.ExpressionParser属性，这里一定是设置为false
            labelEngineLayerProperties2.Expression = strCode;//这里一定要设置

            //labelEngineLayerProperties2
            
            

            labelEngineLayerProperties2.Symbol = textSymbol;

            
            Debug.Print(whereStr_label_style_one);
            Debug.Print(whereStr_label_style_two);
            Console.WriteLine(whereStr_label_style_two);
            // 必须同时使用这两个选项才能显示标注
            annotateLayerProperties.DisplayAnnotation = true;
            #endregion

            geoFeatureLayer_polygon.DisplayAnnotation = true;

            #endregion

            #region 另存为mxd
            //string sdfsdd = @"D:\资料\luo\test.mxd";
            string sdfsdd = string.Format(@"D:\资料\luo\{0}_pageLayout.mxd", qsdwm);
            IMxdContents pMxdC = (IMxdContents)this.axPageLayoutControl1.PageLayout;
            IMapDocument pMapDocument = new MapDocumentClass();
            pMapDocument.New(sdfsdd);
            pMapDocument.ReplaceContents(pMxdC);
            pMapDocument.Save(true, true);
            return;
            #endregion

        }

        private void 开始导出jpg图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _myAeMethods.ExportJpg(this.axPageLayoutControl1.ActiveView, this.axPageLayoutControl1.ActiveView.Extent, 400, @"D:\资料\luo\test_pagelayout.jpg", false);
        }

    }
}
